package com.sinsz.c.result;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sinsz.c.exception.IError;
import com.sinsz.c.exception.SystemError;
import com.sinsz.c.exception.SystemException;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * 返回值对象
 * @author chenjianbo
 */
public class Result {
    /**
     * 状态代码
     */
    private String code;
    /**
     * 消息描述
     */
    private String message;
    /**
     * 返回值
     */
    private Object body;
    /**
     * 错误栈信息
     */
    private Throwable stack;

    private Result(){
    }

    private Result(String message, Object body) {
        this.code = "OK";
        this.message = message;
        this.body = body;
        this.stack = null;
    }

    private Result(IError error, Throwable stack) {
        if (ObjectUtils.isEmpty(error)
                || StringUtils.isEmpty(error.getCode())
                || error.getCode().equals("OK")) {
            throw new SystemException(SystemError.SYSTEM_ERR);
        }
        this.code = error.getCode();
        this.message = error.getMessage();
        this.body = "";
        this.stack = stack;
    }

    /**
     * 无显示返回
     * @return
     */
    public static Result success() {
        return success("");
    }

    /**
     * 数据返回
     * @param body
     * @return
     */
    public static Result success(Object body){
        return success("", body);
    }

    /**
     * 带消息的数据返回
     * @param message
     * @param body
     * @return
     */
    public static Result success(String message, Object body){
        return new Result(message, body);
    }

    /**
     * 错误回执
     * @param error
     * @param stack
     * @return
     */
    public static Result fail(IError error, Throwable stack) {
        return new Result(error, stack);
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getBody() {
        return body;
    }

    public void setBody(Object body) {
        this.body = body;
    }

    public Throwable getStack() {
        return stack;
    }

    public void setStack(Throwable stack) {
        this.stack = stack;
    }
    @Override
    public String toString() {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return super.toString();
    }
}